package com.hgkj.cloud.base.common;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * Description:
 * <p></p>
 *
 * @Author Created by wujj
 * @Date 2023/9/19 16:57
 */
public class ExecutorUtils {
//    public static void main(String[] args) throws Exception {
//        String content = "import java.util.HashMap;\n" +
//                "import java.util.Map;" +
//                "public class Executor { public static void main(String[] args) { " +
//                "Map<String,Integer> map = new HashMap<>();\n" +
//                "        map.put(\"A\",1);\n" +
//                "        map.put(\"B\",2);\n" +
//                "        System.out.println(map); } }";
//        String executor = executor(content);
//        System.out.println(executor);
//
//    }

    public static String executor(String content) throws Exception {
        String fileName = "Executor.java";

        // 将代码保存到文件中
        File sourceFile = new File(fileName);
        FileWriter writer = new FileWriter(sourceFile);
        writer.write(content);
        writer.close();

        // 动态编译
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, null, null, sourceFile.getPath());

        // 加载并执行编译后的类
        URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new File("").toURI().toURL()});
        Class<?> cls = Class.forName("Executor", true, classLoader);
        Method method = cls.getDeclaredMethod("main", String[].class);

        // 重定向标准输出流到ByteArrayOutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        System.setOut(ps);

        // 执行代码片段
        method.invoke(null, (Object) new String[10]);

        sourceFile.delete();
        classLoader.close();
        ps.close();
        baos.close();
        return baos.toString();
    }
}
